const query = require('./db.js')
const util = require('../util/util.js')
// 权限类
class Navigation {
  // 创新新数据
  static createNew(model) {
    return {
      name: model.name,
      parentId: model.parentId,
      type: model.type,
      controller: model.controller,
      action: model.action,
      icon: model.icon,
      authorize: model.authorize,
      summary: model.summary,
      sort: model.sort,
      state: 1
    }
  }
  // 添加权限数据
  static create(arr, callBack) {
    const sqlData = util.convertSQLInsert(arr)
    let sql = `INSERT INTO navigation ${sqlData}; `
    console.log('######')
    query(sql, (err, res) => {
      if (err) {
        callBack(err, null)
        return
      }
      callBack()
    })
  }
  // 根据ID查询数据
  static getById(id, callBack) {
    query(`SELECT * FROM navigation WHERE id = ${id};`, (err, res) => {
      if (err) {
        callBack(err, null)
        return
      }
      callBack(null, res[0])
    })
  }
  // 获取权限列表
  static getList(callBack) {
    query(`SELECT * FROM navigation;`, (err, res) => {
      if (err) {
        callBack(err, null)
        return
      }
      callBack(null, res)
    })
  }
  // 根据角色ID查询权限ID
  static getNavigationIds(roleIds, callBack) {
    const sql = `SELECT navigationId FROM role_navigation WHERE appRoleId IN (${roleIds.join(',')});`
    query(sql, (err, res) => {
      if (err) {
        callBack(err, null)
        return
      }
      callBack(null, res)
    })
  }
  // 根据控制器名和方法名查询权限信息
  static getNavigationByController(controller, action, callBack) {
    const sql = `SELECT * FROM navigation WHERE controller = "${controller}" AND action = "${action}";`
    query(sql, (err, res) => {
      if (err) {
        callBack(err, null)
        return
      }
      callBack(null, res)
    })
  }
  
  // 更新指定权限数据
  static updateById(data, callBack) {
    const sqlData = util.convertSQLUpdate(data)
    query(`UPDATE navigation SET ${sqlData} WHERE id = ${data.id};`, (err, res) => {
      if (err) {
        callBack(err, null)
        return
      }
      if (res.affectedRows == 0) {
        callBack({ message: '未找到权限信息'}, null)
        return
      }
      callBack();
    })
  }
  // 删除指定权限数据
  static delete(id, callBack) {
    query(`DELETE FROM navigation WHERE id = ${id};`, (err, res) => {
      if (err) {
        callBack(err, null)
        return
      }
      if (res.affectedRows == 0) {
        callBack({ message: '未找到权限信息'}, null)
        return
      }
      callBack(null, res);
    })
  }
}
module.exports = Navigation